package com.ys.controller.api.mail;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.mail.MailDraft;
import com.ys.entity.mail.MailMain;
import com.ys.entity.mail.MailReceiver;
import com.ys.entity.shiro.LoginUser;
import com.ys.entity.sys.TsUserChange;
import com.ys.enume.mail.MailEnum;
import com.ys.enume.mail.MailMainEnum;
import com.ys.mapper.mail.MailDraftMapper;
import com.ys.service.mail.MailService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

import lombok.AllArgsConstructor;
import lombok.Data;

@Controller
@RequestMapping("/api/inter/mail")
public class ApiInterMailController {
	
	@Autowired
	private CommonApiService<MailMain> commonApiService;
	@Autowired
	private CommonApiService<MailReceiver> commonApiServiceOfReceive;
	@Autowired
	private MailService mailService;
	@Autowired
	private MailDraftMapper mailDraftMapper;

	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute MailMain cond){
		
		cond.addLeftJoin("TS_UserChange B ON B.Id = A.CreateChangeId")
		.addField("B.UserId createUserId");
		
		return commonApiService.searchLay(cond);
	}

	@RequestMapping("/searchForInbox")
    @ResponseBody
	public LayuiTableVoJA searchForInbox(@ModelAttribute MailReceiver cond){
		
		String loginUserId = ShiroUtils.getUserId();
		
		cond.setUserId(loginUserId)
			.setStatus(1);
		
		cond.addLeftJoin("MAIL_Main B on B.Id = A.MainId")
			.addField("B.Title title, B.Receivers receivers, B.Copyers copyers, B.Tags tags, B.ExtraFile extraFile, B.emergent emergent");
		
		cond.addLeftJoin("TS_UserChange C ON C.Id = B.CreateChangeId")
		.addField("C.UserId createUserId");
		
		return commonApiServiceOfReceive.searchLay(cond);
	}

	@RequestMapping("/searchForOutbox")
    @ResponseBody
	public LayuiTableVoJA searchForOutbox(@ModelAttribute MailMain cond){
		
		String loginUserId = ShiroUtils.getUserId();
		
		cond.setStatus(1);
		
		cond.addLeftJoin("TS_UserChange C ON C.Id = A.CreateChangeId")
			.addField("C.UserId createUserId")
			.where("C.UserId = '" + loginUserId + "'");
		
		return commonApiService.searchLay(cond);
	}

	@RequestMapping("/searchForDustbin")
    @ResponseBody
	public LayuiTableVoJA searchForDustbin(@ModelAttribute MailReceiver cond){
		
		String loginUserId = ShiroUtils.getUserId();
		
		cond.setUserId(loginUserId)
			.setStatus(0);
		
		cond.addLeftJoin("MAIL_Main B on B.Id = A.MainId")
			.addField("B.Title title, B.Receivers receivers, B.Copyers copyers, B.Tags tags, B.ExtraFile extraFile, B.emergent emergent");
		
		cond.addLeftJoin("TS_UserChange C ON C.Id = B.CreateChangeId")
		.addField("C.UserId createUserId");
		
		return commonApiServiceOfReceive.searchLay(cond);
	}
	
	/**
	 * 发送邮件
	 */
	@PostMapping("/sendMail")
    @ResponseBody
	public R sendMail(Model model, HttpServletRequest request, HttpServletResponse response,
			Long draftId,
			String title, Integer emergent, String detail,
			String receiverArr,
			String copyerArr,
			String tagArr){
		
		if (draftId == null) {
			return R.error("无效的邮件来源");
		}
		
		return mailService.sendMail(draftId, title, emergent, detail, receiverArr, copyerArr, tagArr);
	}
	
	/**
	 * 批量删除收件箱
	 */
	@PostMapping("/delete")
    @ResponseBody
	public R delete(Model model, HttpServletRequest request, HttpServletResponse response,
			Long id, String type){
		
		return mailService.delete(id, type);
	}
	
	/**
	 * 保存草稿
	 */
	@PostMapping("/saveDraft")
    @ResponseBody
	public R saveDraft(Model model, HttpServletRequest request, HttpServletResponse response,
			Integer type, // 类型，1只保存，2保存后新建
			Long draftId,
			String title, Integer emergent, String detail,
			String receiverArr,
			String copyerArr,
			String tagArr){
		
		if (type == null) {
			return R.error("保存类型不能为空");
		}
		
		if (draftId == null) {
			return R.error("无效的邮件来源");
		}
		
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		Long createChangeId = tsUserChange.getId();
		
		MailDraft draft = new MailDraft().setId(draftId).setCreateChangeId(createChangeId).queryFirst();
		if (draft == null) {
			return R.error("无效的邮件来源");
		}
		draft.setTitle(title)
			.setEmergent(emergent)
			.setDetail(detail)
			.setReceiverArr(receiverArr)
			.setCopyerArr(copyerArr)
			.setTagArr(tagArr);
		mailDraftMapper.update(draft);
		
		// 保存后，新建一条草稿
		if (type == 2) {
			title = "";
			emergent = MailMainEnum.Emergent.NORMAL.value;
			detail = "";
			String extraFile = "0个附件";
			receiverArr = "[]";
			copyerArr = "[]";
			tagArr = "[]";
			MailDraft entity = MailDraft.mailDraft(title, emergent, detail, extraFile, createChangeId, receiverArr, copyerArr, tagArr, 1);
			mailDraftMapper.insert(entity);
		}
		
		return R.ok();
	}
	
	/**
	 * 批量已读收件箱
	 */
	@PostMapping("/readBatchFromInbox")
    @ResponseBody
	public R readBatchFromInbox(Model model, HttpServletRequest request, HttpServletResponse response,
			String ids){
		
		return mailService.readBatchFromInbox(ids);
	}
	
	/**
	 * 批量删除收件箱
	 */
	@PostMapping("/deleteBatchFromInbox")
    @ResponseBody
	public R deleteBatchFromInbox(Model model, HttpServletRequest request, HttpServletResponse response,
			String ids){
		
		return mailService.deleteBatchFromInbox(ids);
	}
	
	/**
	 * 批量删除草稿箱
	 */
	@PostMapping("/deleteBatchFromDraft")
    @ResponseBody
	public R deleteBatchFromDraft(Model model, HttpServletRequest request, HttpServletResponse response,
			String ids){
		
		return mailService.deleteBatchFromDraft(ids);
	}
	
	/**
	 * 批量删除垃圾箱
	 */
	@PostMapping("/deleteBatchFromDustbin")
    @ResponseBody
	public R deleteBatchFromDustbin(Model model, HttpServletRequest request, HttpServletResponse response,
			String ids){
		
		if (ids == null || ids.length() == 0) {
			return R.error("ID不能为空");
		}
		
		String[] idArr = ids.split(",");
		for (int i = 0; i < idArr.length; i++) {
			Long id = Long.parseLong(idArr[i]);
			String type = MailEnum.Type.DUSTBIN.value;
			mailService.delete(id, type);
		}
		
		return R.ok();
	}
	
	/**
	 * 批量恢复垃圾箱
	 */
	@PostMapping("/rebackBatchFromDustbin")
    @ResponseBody
	public R rebackBatchFromDustbin(Model model, HttpServletRequest request, HttpServletResponse response,
			String ids){
		
		return mailService.rebackBatchFromDustbin(ids);
	}
	
	/**
	 * 批量删除发件箱
	 */
	@PostMapping("/deleteBatchFromOutbox")
    @ResponseBody
	public R deleteBatchFromOutbox(Model model, HttpServletRequest request, HttpServletResponse response,
			String ids){
		
		return mailService.deleteBatchFromOutbox(ids);
	}
	
	/**
	 * 邮件详情信息
	 */
	@PostMapping("/detail")
    @ResponseBody
	public R detail(Model model, HttpServletRequest request, HttpServletResponse response,
			Long id, String type){
		
		return mailService.detail(id, type);
	}
	
	/**
	 * 初始化数据
	 */
	@PostMapping("/initInfoForWrite")
    @ResponseBody
	public R initInfoForWrite(Model model, HttpServletRequest request, HttpServletResponse response){
		
		LoginUser loginUser = ShiroUtils.getLoginUser();
		String loginUserId = loginUser.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		Long createChangeId = tsUserChange.getId();
		
		/*
		 *  获取最新的草稿
		 *  若不存在，则创建一条
		 */
		MailDraft entity = new MailDraft().setCreateChangeId(createChangeId).setStatus(1).setOrderby("A.Id desc").queryFirst();
		if (entity == null) {
			String title = "";
			Integer emergent = MailMainEnum.Emergent.NORMAL.value;
			String detail = "";
			String extraFile = "0个附件";
			String receiverArr = "[]";
			String copyerArr = "[]";
			String tagArr = "[]";
			entity = MailDraft.mailDraft(title, emergent, detail, extraFile, createChangeId, receiverArr, copyerArr, tagArr, 1);
			mailDraftMapper.insert(entity);
		}
		
		// 紧急程度
		Integer emergent = entity.getEmergent();
		
		// 收件人数组
		List<InitInfoDto.ReceiverDto> receiverArr = new ArrayList<InitInfoDto.ReceiverDto>();
		JSONArray receiverJA = JSON.parseArray(entity.getReceiverArr());
		for (int i = 0; i < receiverJA.size(); i++) {
			JSONObject receiverJO = receiverJA.getJSONObject(i);
			String userId = receiverJO.getString("userId");
			String userName = receiverJO.getString("userName");
			receiverArr.add(new InitInfoDto.ReceiverDto(userId, userName));
		}
		
		// 抄送人数组
		List<InitInfoDto.CopyerDto> copyerArr = new ArrayList<InitInfoDto.CopyerDto>();
		JSONArray copyerJA = JSON.parseArray(entity.getCopyerArr());
		for (int i = 0; i < copyerJA.size(); i++) {
			JSONObject copyerJO = copyerJA.getJSONObject(i);
			String userId = copyerJO.getString("userId");
			String userName = copyerJO.getString("userName");
			copyerArr.add(new InitInfoDto.CopyerDto(userId, userName));
		}
		
		// 标签数组
		List<InitInfoDto.TagDto> tagArr = new ArrayList<InitInfoDto.TagDto>();
		JSONArray tagJA = JSON.parseArray(entity.getTagArr());
		for (int i = 0; i < tagJA.size(); i++) {
			JSONObject tagJO = tagJA.getJSONObject(i);
			Long id = tagJO.getLong("id");
			String name = tagJO.getString("name");
			tagArr.add(new InitInfoDto.TagDto(id, name));
		}

		Long id = entity.getId();
		String title = entity.getTitle();
		String detail = entity.getDetail();
		String extraFile = "0个附件";
		String senderUserId = loginUserId;
		String senderUserName = loginUser.getUserName();
		InitInfoDto dto = new InitInfoDto(id, title, detail, extraFile, emergent, receiverArr, copyerArr, tagArr, senderUserId, senderUserName);
		return R.ok(dto);
	}
	@Data
	@AllArgsConstructor
	private static class InitInfoDto{
		private Long id; // 草稿ID
		private String title; // 标题
		private String detail; // 详情
		private String extraFile; // 附件信息
		private Integer emergent; // 紧急程度选项数组
		private List<ReceiverDto> receiverArr; // 收件人数组
		private List<CopyerDto> copyerArr; // 抄送人数组
		private List<TagDto> tagArr; // 标签数组
		private String senderUserId; // 发件人用户ID
		private String senderUserName; // 发件人用户姓名
		
		@Data
		@AllArgsConstructor
		private static class ReceiverDto {
			private String userId;
			private String userName; // 名称
		}
		
		@Data
		@AllArgsConstructor
		private static class CopyerDto {
			private String userId;
			private String userName; // 名称
		}
		
		@Data
		@AllArgsConstructor
		private static class TagDto {
			private Long id;
			private String name; // 名称
		}
	}
}
